// pages/free_zx/free_zx.js
import config from './../../config';
import {
    toast,
    empty,
    message,
    session,
    getOpenId
} from './../../utils/helper';
import {
    getOrderInfo,
    sendMessage,
    getMessage,
    Evaluation,
    getShareInfo,
    getLawyerInfo
} from './../../services/free_zx';
import qs from 'qs';

//获取应用实例
const app = getApp();
//实例化本地缓存
const cookie = new session();

const host = config.service.transfer_protocol + '://' + config.service.domain;

const star = [
    '../../images/Star-fill.png',
    '../../images/Star.png',
    '../../images/Star.png',
    '../../images/Star.png',
    '../../images/Star.png'
];

Page({
    int: 0,
    /**
     * 页面的初始数据
     */
    data: {
        starArray: star,
        disabled: false,
        scrollTop: 1000,
        scroll: {},
        scroll_none: true,
        scroll_view_height: 0,
        send_message_height: 110,
        hidden_more: true,
        info: {},
        list: [],
        val: '',
        qnum: {},
        share_disabled: false,
    },

    //父级页面传递过来的表单参数
    params: {},

    //分享信息
    share_info: {},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        console.log(qs.stringify(options))
        if (empty(options)) {
            console.warn('同学：你这个样子直接打开，是木有办法提交的表单的！');
        } else {
            this.params = options;
        }
        this.getRect();
        //显示当前页面的转发按钮
        wx.showShareMenu({
            withShareTicket: true //是否使用带 shareTicket 的转发详情
        });
    },

    /**
     * 生命周期函数--页面显示/切入前台时触发
     */
    onShow: function() {
        //console.log('onShow');
        this.getDingdan();
        this.lunxun();
    },

    /**
     * 生命周期函数--页面隐藏/切入后台时触发
     */
    onHide: function() {
        //console.log('onHide');
        clearInterval(this.int);
    },

    //页面卸载时触发。如redirectTo或navigateBack到其他页面时。
    onUnload() {
        //console.log('onUnload');
        clearInterval(this.int);
    },

    //获取订单详情
    getDingdan() {
        let that = this,
            params = {
                order_id: this.params.order_id
            };
        getOpenId(openid => {
            params.openid = openid;
            getOrderInfo(params, function(res) {
                if (typeof res == "object") {
                    if (res.status == 'OK') {
                        if (res.data.lawyer_id) {
                            getLawyerInfo({
                                lawyer_id: res.data.lawyer_id
                            }, {
                                success: ({
                                    data
                                }) => {
                                    that.share_info = data;
                                }
                            });
                        }
                        that.getliaotian();
                        that.setData({
                            info: res.data,
                        });
                    } else {
                        message(res.msg);
                    }
                }
            });
        });
    },

    // 获取聊天记录
    getliaotian() {
        let that = this,
            params = {
                order_id: this.params.order_id
            };
        getOpenId(openid => {
            params.openid = openid;
            getMessage(params, function(res) {
                if (typeof res == "object") {
                    if (res.status == 'OK') {
                        res.data.list.map((val, index) => {
                            if (val.role_id == 5) {
                                let tempUserStars = [];
                                for (var i = 0; i < 5; i++) {
                                    if (i < val.star) { // 小于等于star的是满心
                                        tempUserStars[i] = '../../images/Star-fill.png'
                                    } else { // 其他是空心
                                        tempUserStars[i] = '../../images/Star.png'
                                    }
                                }
                                res.data.list[index].starArray = tempUserStars;
                            }
                        });
                        that.setData({
                            list: res.data.list,
                            qnum: res.data.qnum
                        });
                        const client_height = that.data.scroll.scrollHeight - that.data.scroll.scrollTop;
                        if (that.data.scroll_none || client_height == that.data.scroll_view_height) {
                            that.setData({
                                scrollTop: res.data.list.length * 1000
                            });
                        }
                    } else {
                        message(res.msg);
                    }
                }
            });
        });
    },

    //发送消息
    send(e) {
        this.setData({
            disabled: true
        });
        let body = this.data.val,
            that = this,
            params = {
                order_id: this.params.order_id,
                body: body,
            };
        if (!empty(body)) {
            getOpenId(openid => {
                params.openid = openid;
                sendMessage(params, function(res) {
                    if (typeof res == "object") {
                        if (res.status == 'OK') {
                            that.setData({
                                val: '',
                                info: Object.assign(that.data.info, {
                                    reminders: 0
                                }),
                                scrollTop: that.data.list.length * 1000
                            });
                        } else {
                            message(res.msg);
                        }
                    }
                    that.setData({
                        val: '',
                        disabled: false
                    });
                    that.getliaotian();
                });
            });
        } else {
            this.setData({
                disabled: false
            });
        }
    },

    //聊天输入内容
    bindChange(e) {
        this.setData({
            val: e.detail.value
        });
    },

    //下拉刷新
    onPullDownRefresh: function(e) {
        this.getliaotian();
        wx.stopPullDownRefresh();
    },

    //催单
    evaluation(e) {
        let that = this,
            params = e.currentTarget.dataset;
        that.setData({
            disabled: true
        });
        getOpenId(openid => {
            params.openid = openid;
            Evaluation(params, {
                success: () => {
                    toast('催单成功')
                    if (params.index == -1) {
                        that.setData({
                            info: Object.assign(that.data.info, {
                                reminders: 0
                            })
                        });
                        that.getDingdan();
                    } else {
                        that.data.list[params.index].reminders = 0;
                        that.setData({
                            list: that.data.list
                        });
                        that.getliaotian();
                    }
                },
                complete: () => {
                    that.setData({
                        disabled: false
                    });
                }
            });
        });
    },

    // 轮询
    lunxun() {
        let that = this;
        this.int = setInterval(function() {
            that.getliaotian()
        }, 5 * 1000)
    },

    //获取聊天窗高度
    getRect: function() {
        let that = this;
        wx.createSelectorQuery().select('#the-id').boundingClientRect(function(rect) {
            that.setData({
                scroll_view_height: rect.height
            });
        }).exec()
    },

    //聊天内容滑动事件
    scroll(e) {
        this.setData({
            scroll: e.detail,
            scroll_none: false
        });
    },

    //点击加号,展示更多功能
    open_more: function() {
        if (this.data.hidden_more) {
            this.setData({
                hidden_more: false,
                send_message_height: 545 + 110
            })
        } else {
            this.close_more();
        }

    },

    //关闭更多功能
    close_more: function() {
        this.setData({
            hidden_more: true,
            send_message_height: 110
        })
    },

    //跳转到评价页面
    tiao_pingJia: function() {
        let that = this;
        getOpenId(openid => {
            that.params.openid = openid;
            wx.navigateTo({
                url: '../../pages/pingjia/pingjia?' + qs.stringify(this.params)
            })
        });
    },

    //跳转到律师主页
    tiao_lawyer: function(e) {
        wx.navigateTo({
            url: '../../pages/lawyer/lawyer?' + qs.stringify(e.currentTarget.dataset)
        })
    },

    //红包
    hongbao() {
        let that = this;
        getOpenId(openid => {
            that.params.openid = openid;
            wx.navigateTo({
                url: '../../pages/hongbao/hongbao?' + qs.stringify(this.params),
                success: () => {
                    that.close_more();
                }
            })
        });
    },

    //付费
    fufei() {
        let that = this;
        getOpenId(openid => {
            that.params.openid = openid;
            wx.navigateTo({
                url: '../../pages/pay2/pay2?' + qs.stringify(this.params),
                success: () => {
                    that.close_more();
                }
            })
        });
    },

    //分享
    onShareAppMessage() {
        let that = this,
            params = {};
        if (!empty(this.share_info.lawyer_extend)) {
            params = {
                title: !empty(that.share_info.lawyer_extend.share_title) ? that.share_info.lawyer_extend.share_title : '分享给你一个专业律师，法律问题可以找他',
                imageUrl: !empty(that.share_info.lawyer_extend.share_img_pic) ? host + that.share_info.lawyer_extend.share_img_pic : "/images/article_list_default.png"
            };
        } else {
            params = {
                title: '分享给你一个专业律师，法律问题可以找他',
                imageUrl: "/images/article_list_default.png"
            };
        }
        that.setData({
            share_disabled: true,
        })
        return {
            title: params.title,
            path: '/pages/lawyer/lawyer?' + qs.stringify({
                lawyer_id: that.share_info.id
            }),
            imageUrl: params.imageUrl,
            success: (res) => {
                if (!empty(res.shareTickets)) {
                    wx.getShareInfo({
                        shareTicket: res.shareTickets,
                        success: (res) => {
                            getOpenId(openid => {
                                res.openid = openid;
                                res.order_id = that.params.order_id;
                                getShareInfo(res, {
                                    complete: (res) => {
                                        that.setData({
                                            share_disabled: false,
                                        })
                                    }
                                });
                            });
                        },
                        fail: () => {
                            that.setData({
                                share_disabled: false,
                            })
                        }
                    })
                } else {
                    that.setData({
                        share_disabled: false,
                    })
                }
            },
            fail: () => {
                that.setData({
                    share_disabled: false,
                })
            }
        }
    },
})